#!/usr/bin/env bash

# General tools for manipulating patches
# and dealing with patches.

lookup_patchset()
{
  \typeset paths lookup_path

  if [[ -z "$1" ]]
  then
    echo "Usage: rvm patchset show name"
    return 1
  fi

  paths=($(__rvm_ruby_string_paths_under "$rvm_path/patchsets" | sort -r))

  for lookup_path in "${paths[@]}"
  do
    if [[ -s "$lookup_path/$1" ]]
    then
      \command \cat "$lookup_path/$1"
      return 0
    fi
  done

  return 1
}

# Returns the path used to look for a patch given a specific name.
__rvm_patch_lookup_path()
{
  echo "/"
  [[ -z "${rvm_patch_original_pwd:-""}" ]] || echo "$rvm_patch_original_pwd/"
  echo "$PWD/"
  __rvm_ruby_string_paths_under "$rvm_patches_path" | __rvm_sed 's/$/\//' | sort -r
  return $?
}

__rvm_expand_patch_name()
{
  \typeset name level expanded_patch_name not_required_patches
  not_required_patches="optional default ${_system_name_lowercase}"
  name="${1:-""}"
  level="${2:-}"
  [[ -n "$name" ]] || return 0
  if
    expanded_patch_name="$(
      rvm_ruby_string="${rvm_ruby_string}" lookup_patchset "$name"
    )"
  then
    echo "${expanded_patch_name}"
  elif
    [[ " $not_required_patches " != *" $name "* ]]
  then
    echo "${name}${level:+%}${level:-}"
  fi
}

# Return the full patch for a given patch.
__rvm_lookup_full_patch_path()
{
  \typeset extension patch_path directory directories __old_IFS
  # Absolute path, pwd and then finally the rvm patches path.
  __old_IFS="$IFS"
  IFS=$'\n'
  directories=($( __rvm_patch_lookup_path ))
  IFS="$__old_IFS"
  for directory in "${directories[@]}"
  do
    for extension in "" .patch .diff
    do
      patch_path="${directory}${1}${extension}"
      # -s reports directories too - so additional check -f needed
      if
        [[ -s "$patch_path" && -f "$patch_path" ]]
      then
        echo "$patch_path"
        return 0
      fi
    done
  done
  if
    __rvm_string_match "$1" "http://*" "https://*" &&
    file_exists_at_url "$1"
  then
    echo "$1"
  fi
}
